package util

import (
	"cloud-disk/global/define"
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	uuid "github.com/satori/go.uuid"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

func Sha1Crypt(data []byte) string {
	hash := sha1.New()
	hash.Write(data)
	return hex.EncodeToString(hash.Sum(nil))
}

func UUID() string {
	v4 := uuid.NewV4()
	return v4.String()
}

type UserClaim struct {
	Id       int
	Identity string `json:"identity"`
	Email    string `json:"email"`
	jwt.RegisteredClaims
}

func CreateToken(id int, identity string, email string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaim{
		Id:       id,
		Identity: identity,
		Email:    email,
	})
	//timeStamp := fmt.Sprintf("%x", time.Now().Unix())
	signedString, err := token.SignedString([]byte(define.Conf.Token.Key))
	if err != nil {
		fmt.Println(err)
		return "", err
	}

	return signedString, nil
}

func Captcha(n int) string {
	rand.Seed(time.Now().Unix())
	var code string
	for i := 0; i < n; i++ {
		code += strconv.Itoa(rand.Intn(10))
	}
	return code
}
func MixCaptcha(n int) string {
	rand.Seed(time.Now().Unix())
	str := "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
	var code string
	for i := 0; i < n; i++ {
		code += string(str[rand.Intn(len(str))])
	}
	return code
}
func FileSha1(data []byte) string {
	hash := sha1.New()
	hash.Write(data)
	return hex.EncodeToString(hash.Sum(nil))
}
func FileExt(fname string) string {
	dot := strings.LastIndex(fname, ".")
	ext := ""
	if dot == -1 {
		ext = ""
	} else {
		ext = fname[dot:]
	}
	return ext
}
